//
//  QuXuanTiVC.m
//  ZhiBoYuan
//
//  Created by apple on 2018/4/20.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "QuXuanTiVC.h"

#import "QuXuanTiCell.h"

#import "ShaiXuanViewController.h"

#import "PaperViewControllerBuild.h"

static NSString *ident = @"QuXuanTiCell";



@interface QuXuanTiVC ()
<
UITableViewDelegate,
UITableViewDataSource
>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger pageIndex;

@property (nonatomic,strong)NSMutableArray *selArr;


@property(nonatomic,strong) UILabel *tittleLabel;
/*
 0
 1
 2
 3
 4
 5
 6
 */
@property(nonatomic,strong)NSMutableArray *arr;


//@property(nonatomic,strong)NSMutableArray *shaiXuanArr;

@property(nonatomic,strong)NSMutableDictionary *shaiXuanDic;
@end

@implementation QuXuanTiVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"试卷详情页";
    
    NSLog(@"选题页面");
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, 50)];
    view.backgroundColor =hui1Color;
    
    [self.view addSubview:view];
    
    [view addSubview:self.tittleLabel];
    
    [self.view addSubview:self.tableView];
    
    UIBarButtonItem *shaiXuan = [[UIBarButtonItem alloc]initWithTitle:@"筛选" style:0 target:self action:@selector(shaiXuanSender) ];
    
    UIBarButtonItem *quRen =[[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(openSender)];
    
    
    
    self.navigationItem.rightBarButtonItems =@[shaiXuan,quRen];
    [self getdate];
}

#pragma mark ----------------------- 筛选 ------------------------
- (void)shaiXuanSender {
    
    NSLog(@"筛选");
    
    
    ShaiXuanViewController *vc = [[ShaiXuanViewController alloc]init];
//    vc.xuanTi = YES;
    
    vc.shaiXuan = ShaiXuanTypeXuanTi;
    
    vc.shaiXuanDic = ^(id dictory) {
        
        
        self.shaiXuanDic = [Helper newShaiXuanFromDictionary:dictory];
        
        NSLog(@"dictory == %@",self.shaiXuanDic);
        
        
        self.pageIndex =1;
        [self getdate];
        
    };
    
    
//    vc.block = ^(NSMutableArray *arr) {
//        NSLog(@"筛选结果= %@",arr);
//
//        _shaiXuanArr = [NSMutableArray array];
//
//
//        for (NSString *str in arr) {
//            [_shaiXuanArr addObject:str];
//        }
//        self.pageIndex =1;
//
//        [self getdate];
//
//    };

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    }
    else
    {
        self.modalPresentationStyle = UIModalPresentationCurrentContext;
    }
    vc.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [self.tabBarController presentViewController:vc animated:YES completion:nil];
    
}



-(UILabel *)tittleLabel{
    if (!_tittleLabel) {
        _tittleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, ScreenWidth, 50)];
        _tittleLabel.backgroundColor = hui1Color;
        
        _tittleLabel.text = @"数据加载中。。。";
        
    }
    return _tittleLabel;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray  = [NSMutableArray array];
    }
    return _dataArray;
}


-(void)getdate
{
    SGParameter *parameter  = [[SGParameter alloc] init];
    
    parameter.body          = @{@"xueduan_id":@""
                                ,@"xueke_id":@""
                                ,@"nianji_id":@""
                                ,@"knowledge_point_id":@""
                                ,@"page":[NSString stringWithFormat:@"%zd",self.pageIndex]
                                ,@"page_count":@"10"
                                };
    
    
    
    
    // 筛选参数
    if (self.shaiXuanDic.count > 0) {
        
//        ShaiXuan *s = [[ShaiXuan alloc]initWithDictionary:[Helper shaiXuanFromArr:self.shaiXuanArr]];
        
        ShaiXuan *s = [[ShaiXuan alloc]initWithDictionary:self.shaiXuanDic];

        

        
        parameter.body          = @{@"xueduan_id":s.xueDuan  // 学段id
                                    ,@"xueke_id":s.xueKe  // 学科id
                                    ,@"nianji_id":s.nianJi //年级id
                                    ,@"knowledge_point_id":s.zhiShiDian  //知识点id
                                    ,@"page":[NSString stringWithFormat:@"%zd",self.pageIndex]
                                    ,@"page_count":@"10"
                                    };

    }

    
    NSString *lastUrl       = @"g=Client&m=Question&a=questionList";
    
//    __weak __typeof(&*self)weakSelf = self;
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
        
        NSDictionary *dic = responseObject;
//        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
//        NSString *resultStr =[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        NNSLog(@"%@",dic);

        NSMutableArray *arr = dic[@"data"][@"question_list"];
        
        NNSLog(@"question_list = %@",arr);

        if (self.pageIndex == 1)
        {
            [self.dataArray removeAllObjects];
        }
        for (id dic  in arr) {
            [self.dataArray addObject:dic];
        }
        
        NSMutableArray *danArr=[NSMutableArray array];
        
        NSMutableArray *duoArr= [NSMutableArray array];
        NSMutableArray *wenArr= [NSMutableArray array];
        
        
        for (NSDictionary *dic in self.dataArray) {
            
            if ([dic[@"ques_model"] integerValue] == 0)
            {
                [danArr addObject:dic];
            }
            else if ([dic[@"ques_model"] integerValue] == 1)
            {
                [duoArr addObject:dic];
            }
            else
            {
                [wenArr addObject:dic];
            }
            
        }
        
        self.tittleLabel.text = [NSString stringWithFormat:@"共%zd题（单选:%zd道,多选:%zd道,问答:%zd道）",arr.count,danArr.count, duoArr.count,wenArr.count];
        
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];

        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
}



#pragma mark -----------------------确认------------------------
-(void)openSender{
    if (self.blockAdd) {
//        self.blockAdd(self.selArr);
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(NSMutableArray *)selArr{
    if (!_selArr) {
        _selArr = [NSMutableArray array];
        
    }
    return _selArr;
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT + 50, ScreenWidth, Screenheight-NAVIGATION_BAR_HEIGHT-50) style:(UITableViewStylePlain)];
        
        _tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
        
        _tableView.rowHeight = UITableViewAutomaticDimension;
        
        _tableView.delegate = self;
        
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        
        [_tableView registerNib:[UINib nibWithNibName:ident bundle:nil] forCellReuseIdentifier:ident];
        
        // 下拉刷新
        _tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            
            [self.shaiXuanDic removeAllObjects];
            
            self.pageIndex = 1;
            
            [self getdate];
            

        }];
        
        //         上拉加载
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            if ( self.pageIndex < -1 ) {  self.pageIndex = 1;  }
            
            
            self.pageIndex ++;
            [self getdate];
            

        }];
    }
    return _tableView;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QuXuanTiCell *cell= [tableView dequeueReusableCellWithIdentifier:ident forIndexPath:indexPath];
    
    [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
    
    Questiion *q = [[Questiion alloc]initWithDictionary:self.dataArray[indexPath.row]];
    
    
     cell.questiion = q;
    
    if ([self.selArr containsObject:[NSString stringWithFormat:@"%zd",indexPath.row]])
    {
        [cell.addbutton setImage:[UIImage imageNamed:@"删除-1"] forState:(UIControlStateNormal)];
    }
    else
    {
        [cell.addbutton setImage:[UIImage imageNamed:@"添加"] forState:(UIControlStateNormal)];
    }
    
    BTN_MSG_FUNC(cell.addbutton, buttonSender:);
    
    
    
    
    return cell;
    
}


#pragma mark -----------------------选题------------------------

- (void)buttonSender:(UIButton *)sender {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(QuXuanTiCell *)  [[sender superview] superview]];
    
    Questiion *q = [[Questiion alloc]initWithDictionary:self.dataArray[indexPath.row]];
    
    
    if ([self.selArr containsObject:[NSString stringWithFormat:@"%zd",indexPath.row]]) {
        
        
        SGParameter *parameter  = [[SGParameter alloc] init];
        
        parameter.body          = @{@"paper_id":self.paper_id,
                                    @"question_id":q.id
                                    };
        
        NSString *lastUrl       = @"g=Client&m=Paper&a=delQuestion";
        
        //    __weak __typeof(&*self)weakSelf = self;
        
        [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
            
            NSDictionary *dic = responseObject;
            
//            NNSLog(@"%@",dic);
            NNSLog(@"删除 question_list = %@",dic);
            
            
            if ([dic[@"status"] integerValue] == 200)
            {
                
                [self.selArr removeObject:[NSString stringWithFormat:@"%zd",indexPath.row]];
                
                [_tableView reloadData];
                
//                self.title = [NSString stringWithFormat:@"选题100/%zd",self.selArr.count];

            }
            else
            {
               [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:3];
            }
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            
        }];

    }else{
        SGParameter *parameter  = [[SGParameter alloc] init];
        
        parameter.body          = @{@"paper_id":self.paper_id,
                                    @"question_ids":q.id };
        
        NSString *lastUrl       = @"g=Client&m=Paper&a=addQuestion";
        
        //    __weak __typeof(&*self)weakSelf = self;
        
        [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
            
            NSDictionary *dic = responseObject;
            
            NNSLog(@"%@",dic);
            
//            NSMutableArray *arr = dic[@"data"];
            
            if ([dic[@"status"] integerValue] == 200)
            {
                [self.selArr addObject:[NSString stringWithFormat:@"%zd",indexPath.row]];
                
                [_tableView reloadData];
                
//                self.title = [NSString stringWithFormat:@"选题100/%zd",self.selArr.count];
            }
            else
            {
                [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:3];
            }
            
            NNSLog(@"添加  question_list = %@",dic);

        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            
        }];


    }
 
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
 
    PaperViewController * paper;
    paper = [PaperViewControllerBuild createIntelligentAllAnalyViewControllerWithData:@{}];
    paper.ID = [_dataArray[indexPath.row] valueForKey:@"id"];
    
    paper.answerType = @"question_id";
    paper.url = QuestionInfo;
    paper.isComeFromShongCang = YES;
    [ZYCurrentViewController().navigationController pushViewController:paper animated:YES];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
